
/**
 * mrjy全局变量
 * @Object
 * @存取公共方法和公共变量
 */
var mrjyGlobal = {};
/**
 * 将请求地址加上时间戳，防止浏览器缓存
 * @author Javin : isUse =true
 */
function getTimeURL(url) {
	if (url.indexOf("?") == -1) {
		url += "?timeStamp=" + new Date().getTime();
	} else {
		url += "&timeStamp=" + new Date().getTime();
	}
	return encodeURI(url);
}


    //@mengfei 封装一个获取个人信息页面的方法
    function loginSuccessPage(name, picUrl,content) {
        var loginSuccessPage = '<a href="#" class="login-photo-page"><img src="' + picUrl + '" alt="" /></a>' +
            '<a href="#" class="person-setting-a"><span class="person-setting" id="person-setting" >个人设置</span></a>' +
            '<h1>' + name + '</h1>' +
            '<div class="personPageContent">'+ content+'</div>';
        $('.personPage').empty().append(loginSuccessPage);
    }
    
    
     //@mengfei 封装了一个获取个人信息的方法
    function loginSuccess(name, picUrl,Id) {
        //@mengfei 登陆成功渲染用户信息
        var loginRegisterSucss = '<div class="login-register-sucss ">' +           
            '<span class="glyphicon glyphicon-triangle-bottom font-ico-list " ></span>' +
            '<a href="personPage.html?id='+Id+'" class="login-register-picA"><img src="' + picUrl + '" /></a>' +
            '<a href="personPage.html?id='+Id+'" class="login-register-name-a"><span>' + name + '</span></a>' +
            '</div>' +
            '<ul id="setting-right" class="setting-right">' +
            '<li class="setting-login-register-active"><a href="personPageMessage.html">我的消息</a></li>' +
            '<li><a href="personPageKing.html">会员中心</a></li>' +
            '<li><a href="personPageSetting.html">个人设置</a></li>' +
            '<li><a href="" class="exit">退出</a></li>' +
            '</ul>';

        //关闭弹出框
        $('.mfp-close').click();
        //隐藏登录注册按钮
        $('.open-popup-link > span').addClass('displayLoginRegister');
        //渲染列表
        $('#MainPersonSettings').empty().append(loginRegisterSucss);
        //鼠标移入列表显示背景
        $('#setting-right > li').mouseenter(function () {
            $(this).addClass('setting-login-register-active').siblings().removeClass('setting-login-register-active');
        })

        //移入箭头
        $('.font-ico-list').mouseenter(function () {
            if ($(this).hasClass('glyphicon-triangle-bottom')) {
                $(this).removeClass('glyphicon-triangle-bottom').addClass('glyphicon-triangle-top')
                $('#setting-right').removeClass('setting-right');
            } else {
                $(this).removeClass('glyphicon-triangle-top').addClass('glyphicon-triangle-bottom')
                $('#setting-right').addClass('setting-right');
            }
            //移出列表
            $('#setting-right , .leaveMouseArr').mouseleave(function () {
                $('#setting-right').addClass('setting-right');
                $('.font-ico-list').removeClass('glyphicon-triangle-top').addClass('glyphicon-triangle-bottom')
            })
        });

        //点击退出
        $('.exit').click(function () {
		    clearAllCookie();

		     //	退出
		    $.ajax({
		        url: mrjyUrl + 'common/util/logout.do',
		        type: 'get',
				data:{},
		        success: function (data) {
		            console.log(data);
		        $('#MainPersonSetting').html('');
		        $('.open-popup-link > span').removeClass('displayLoginRegister');
		       
            	
		
		        }
		    })
       
		

        });
    }
    
/**
 * 对象转化为数组
 * @author Javin : isUse = true
 */
function cJSON(jsonObj) {
	console.log(JSON.stringify(jsonObj));
	return JSON.stringify(jsonObj);
}

/**
 * 对象转化为数组
 * @author Javin : isUse = true
 */
function aJSON(jsonObj) {
	console.log(JSON.stringify(jsonObj));
	return JSON.stringify(jsonObj);
}

/**
 * 查看元素是否包含在对象或数组中
 * @author Javin : isUse = true
 */
function isContain(obj, objArr) {
	if (!objArr) return false;
	for (var o in objArr) {
		if (obj == objArr[o]) return true;
	}
	return false;
}

/**
 * 删除字符串最后","字符
 * @author Javin : isUse = true
 */
function removeComma(str) {
	if (str){
		var lastIndex = str.length - 1;
		if (str[lastIndex] == ",") {
			str = str.substring(0, lastIndex);
		}
	}
	return str;
}

/**
 * 获取URL的传参值，对通过 escape() 编码的字符串进行解码。
 * @author Javin : isUse = true
 */
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

/**
 * 获取URL的传参值，先对对 encodeURI() 函数编码过的 URI 进行解码，再对通过 escape() 编码的字符串进行解码。解决中文乱码
 * @author Javin : isUse = true
 */
function getQueryString2(name){
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(decodeURI(r[2]));
	return null;
}

/**
 * 比较两个时间戳的大小
 * @author Javin : isUse = true
 */
function compareTime(time1, time2) {
	if (parseInt(time1) + 10800000 > parseInt(time2))
		return false;
	else
		return true;
}

/**
 * 将getTime的时间值(Long)转成 年-月-日 时:分
 * @author Javin : isUse = true
 */
function getTimeStr(timeSec){
	var d = new Date(timeSec);
	var timeStr = d.getFullYear() + "-" + timeFormat(d.getMonth() + 1) + "-" + timeFormat(d.getDate()) + " " + timeFormat(d.getHours()) + ":" + timeFormat(d.getMinutes());
	return timeStr;
};
/**
 * 将getTime的时间值(Long)转成 年-月-日 
 * @author Javin : isUse = true
 */
function getTimeYYYYMMDD(timeSec){
	var d = new Date(timeSec);
	var timeStr = d.getFullYear() + "-" + timeFormat(d.getMonth() + 1) + "-" + timeFormat(d.getDate()) ;
	return timeStr;
};
function timeFormat(num){
	var oneNum = num / 10;
	if(oneNum < 1) num = "0" + num;
	return num;
};


/**
 * 判断用户浏览的设备，PC、phone
 * @author Javin : isUse = true
 */
function browserRedirect() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
    	return "phone";
    } else {
    	return "pc";
    }
}

var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
            iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
            qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
    }(),
    language:(navigator.browserLanguage || navigator.language).toLowerCase()
}

/*
 清空所有cookie
 */
 function clearAllCookie() {  
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);  
    if(keys) {  
        for(var i = keys.length; i--;)  
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()  
    }  
}  

/**
 * 定时器
 * @param {Object} timeNum 定时时间（s） 
 * @param {Object} successDB 定时完成执行函数
 */
function timeCount(timeNum,successDB){
	var time2 = setTimeout("timeCount()",1000);
	if(timeNum<=0)
		{
			clearTimeout(time2);
			successDB&&successDB();
			timeNum=0;
			return;
		}
	timeNum = timeNum-1;
	return timeNum;
}

//设置cookie
function setCookie(name,value){
	sessionStorage[name] = value;
//  document.cookie = name+'='+escape(value);  
}

function getCookie(name){
	return sessionStorage[name];
}

function deleteCookie(name){
	delete sessionStorage[name];
}

function initBack(backFunc){
	if(!backFunc) backFunc = function(){
		history.go(-1);
	}
	$(".mrjy-turn-back").tap(backFunc);
}


/**
 * 表单数据对象转换 通过serializeArray()
 * @author Javin : isUse = true
 */
function formArrayToJson(arrayData){
	var serializeObj={};
	$(arrayData).each(function(){
		serializeObj[this.name]=this.value;
	})
	return serializeObj;
}

/**
 * 检测对象是否为空
 * @author Javin : isUse = true
 */
function checkObjIsNull(obj){
	for(var o in obj){
		return false;
	}
	return true;
}

/**
 * 中间字符串用*** 代替
 * @author Javin : isUse = true
 */
function hiddenPartValue(obj){
	return{
		"mobilePhone":function(obj){
//			console.log(obj);
			return obj.substr(0,3) + "****" + obj.substr(7,4);
		},
		"email":function(obj){
//			console.log("email:"+obj)
			var arr = obj.split("@");
			var before = arr[0];
			if (before.length>5) {
				var str = before.substr(0,3);
				for(var i =0;i<before.length-5;i++){
					str += "*";
				}
				str += before.substr(before.length-2,2);
				return str +"@"+ arr[1];
			}else{
				return obj;	
			}
		}
	}
}


/**
 * 请求URL拼接， url.do结尾
 * @author Javin : isUer = true
 */
function appendParm(url ,obj){
	var newUrl = url + "?";
	var parmStr = "";
	for(var o in obj){
		parmStr = "&" + o + "=" + obj[o];
		newUrl += parmStr;
	}
	return newUrl;
}

/**
 * 请求URL拼接，数组参数， url.do结尾
 * @author Javin : isUer = true
 */
function appendParms(url, obj){
	var appendUrl = url + "?";
	var parmArr = [];
	var parmValue = null;
	for(var o in obj){
		parmValue = obj[o];
		if($.isArray(parmValue)){
			for(var j in parmValue){
				parmArr.push(o + "=" + parmValue[j])
			}
		}else{
			parmArr.push(o + "=" + parmValue);
		}
	}
	appendUrl += parmArr.join("&");
	return appendUrl
}

/**
 * 是否为微信浏览器对象
 * @author Javin : isUer = true
 */
function isWeixinNavigator(){
	var navigatorName = navigator.userAgent.toLowerCase();
	if(navigatorName.indexOf('micromessenger') > 0) return true;
	return false
}

function supportCss3(style) {
	var prefix = ['webkit', 'Moz', 'ms', 'o'],
		i, humpString = [],
		htmlStyle = document.documentElement.style,
		_toHumb = function(string) {
			return string.replace(/-(\w)/g, function($0, $1) {
				return $1.toUpperCase();
			});
		};
	for(i in prefix) humpString.push(_toHumb(prefix[i] + '-' + style));
	humpString.push(_toHumb(style));
	for(i in humpString)
		if(humpString[i] in htmlStyle) return true;
	return false;
}

function initWeUITabbar(){	
	var userId = mrjyGlobal.userData.id;
		//获取通知里的未读通知消息
		$.getJSON(getTimeURL(mrjyUrl + "maintain/msgInfo/queryMyPageMessageByUserId.do?"+userId),function(data){
			var UnreadNum = data.count;
			if(UnreadNum>0){
				var MessageNotice = document.createElement("span");
				document.getElementById("weui-tabbar_span").appendChild(MessageNotice);
				$(MessageNotice).addClass("weui-badge weui-badge_dot badge_dot").html();
			}
		});
	$(".weui-tabbar__item").on("click",function(){
		console.log($(this));
		$(this).addClass("weui-bar__item_on").siblings().removeClass("weui-bar__item_on");
		var dataId = $(this).data("id");
		if(dataId == 1){//weClasses
			window.location = "../../phoneWeb/weClasses/weClasses.html";	
		}else if(dataId == 2){//weQA
			window.location = "../../phoneWeb/weQA/weQA.html";
		}else if(dataId == 3){//weInfo
			window.location = "../../phoneWeb/weInfo/weInfo.html";
		}
		
	});
}

//手机号码验证
function validMobilePhone(mobilePhone){
//	console.log(23);
	var flag = true ;
	var tel = /^(130|131|132|133|134|135|136|137|138|139|147|150|151|152|153|154|155|156|157|158|159|170|177|176|180|181|182|183|184|185|186|187|188|189)\d{8}$/;
	//验证手机号码是否正确
    if(!mobilePhone || !tel.test(mobilePhone)){
    	//weui.topTips('请输入正确的手机号码');
    	flag = false;
    }
	
	return flag;
}

//校验密码：只能输入6-20个字母、数字、下划线  
function isPasswd(s){  
var patrn=/^(\w){6,20}$/;  
if (!patrn.exec(s)) return false
return true
}

//校验用户姓名：只能输入1-16个字串由字母数字下划线组成
function isTrueName(s){  
var patrn=/^[\u4e00-\u9fff\w]{1,16}$/ ;  
if (!patrn.exec(s)) return false
return true
}  

//验证码倒计时

var countdown = 60;
function settime(obj) { 
    if (countdown == 0) { 
        obj.removeAttribute("disabled");    
        obj.value="获取验证码"; 
        countdown = 60; 
        return;
    } else { 
        obj.setAttribute("disabled", true); 
        obj.value="重新发送(" + countdown + ")"; 
        countdown--; 
    } 
	setTimeout(function() { 
    settime(obj) }
    ,1000) 	
}
//邮箱验证
function isEmail(str){ 
var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/; 
return reg.test(str); 
} 

//检查用户是否会员
function checkPayment(success) {
	$.ajax({
		type: "GET",
		url: getTimeURL(mrjyUrl + "payment/userBalance/checkPayment.do"),
		dataType: "json",
		async: false,
		success: function(data) {//data = ok
			if(success)success(data);
		}
	});
}

/*检查是否为会员*/
function isVip(userId,success){
	var _userId = "";
	if(userId != undefined){
		_userId = userId;
	}
	$.ajax({
      	type:"get",
      	url:getTimeURL(mrjyUrl +"maintain/userMemberInfo/isVip.do"),
      	async:false,
      	dataType:"json",
      	data:{"userId":_userId},
      	success: function(data){//err_code = 0 会员，err_code =1 非会员,-1 未登录
           	if(success)success(data);
	    }  
  	});
};

function isBindingByOpenId(openId,success){
	$.getJSON(getTimeURL(mrjyUrl + "maintain/userInfo/isBindedByOpenId.do?openId="+openId),function(data){
		if(success)success(data);
	})
}


/*传进字符串和最大限制长度，返回长度*/
function checkStrLengths(str,maxLength){
	var maxLength = maxLength ;
	var result = 0 ;
	if(str && str.length > maxLength){
		result = maxLength;
	}else{
		result = str.length ;
	}
	return result ; 
}


function filteremoji(value){
	var ranges = [ 
	'\ud83c[\udf00-\udfff]',
	'\ud83d[\udc00-\ude4f]',
	'\ud83d[\ude80-\udeff]' 
	];
	value = value.replace(new RegExp(ranges.join('|'), 'g'), '');
	return value;
}

/**
 * 对日期进行格式化，
 * @param date 要格式化的日期
 * @param format 进行格式化的模式字符串
 *     支持的模式字母有：
 *     y:年,
 *     M:年中的月份(1-12),
 *     d:月份中的天(1-31),
 *     h:小时(0-23),
 *     m:分(0-59),
 *     s:秒(0-59),
 *     S:毫秒(0-999),
 *     q:季度(1-4)
 * @return String
 */
function dateFormatfunc(date, format){

    date = new Date(date);
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };

    format = format.replace(/([yMdhmsqS])+/g, function(all, t){
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        }
        else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
}

	//@mengfei 获取url的id	
	function getUrlId(){
		   	var str = document.location.href;
			var arr = [];
			arr = str.split("=");
			var numId = arr[1];
			return numId;
	}

function personInfo(obj) {
    console.log(obj)
    window.location.href='personPage.html?id='+obj;
}


function alterImgFunc(picName,userImg,headImgUrl) {
    var result='/';
    if (picName!=null&&picName.length>1){
        if(picName.indexOf('/')==-1){
            //没找到，说明是我们后台上传的，需要拼接\
            console.log('picName------picName ')
            result=icoPicUrl+picName;
        }
        return result;
    }else if (userImg!=null&&userImg.length>1){
        if(userImg.indexOf('/')==-1){
            //没找到，说明是我们后台上传的，需要拼接\
            console.log('userImg------userImg ')
            result=icoPicUrl+userImg;
        }
        return result;
    }else if(headImgUrl!=null&&headImgUrl.length>1){
        console.log('headImgUrl------headImgUrl ')
        result=headImgUrl;
        return headImgUrl;
    }else {
        return result;
    }


    var result='---------';
    return result;
    /*if (len(headImgUrl)>4){
        return headImgUrl;
    }else {
        result=mrjyFile+'maintain/userpic/'+userImg;
        console.log(result);
        return result;
    }*/
}

function toOpenVIP(obj) {
    location.href="to_payment_weixin.html";
}